#!/bin/bash

# 目录指定，最终会在这个目录下 增加/发布单/项目
# /Users/wangjie/code/java/马来-ipo
input_path=$(pwd)
# 提取直到 "Documents/" 的部分
ops_base_path="${input_path%%/Documents/*}/Documents/ops"
ops_global_path="${input_path%%/Documents/*}/Documents/ops/ops_global.properties"
clone_dir=$(of "read_config" "code_path" "" "$ops_global_path")
jz_clone_dir=$(of "read_config" "jz_code_path" "" "$ops_global_path")
ops_user=$(of "read_config" "ops_user" "" "$ops_global_path")
ops_auth=$(of "read_config" "ops_auth" "" "$ops_global_path")
ops_auth_type=$(of "read_config" "ops_auth_type" "" "$ops_global_path")
#clone_dir="$HOME/meili/vangelis.wang/103/Documents/code/ops"
#clone_dir="$HOME/code/java/ops"
log_file="$ops_base_path/log/$(date +'%Y-%m-%d')-dops.log"  # 你可以修改为其他日志路径
if [ ! -d "$ops_base_path/log" ]; then
  mkdir -p "$ops_base_path/log"
fi
if [ ! -f "$log_file" ]; then
  touch "$log_file"
fi

# 日志函数
log() {
    local message=$1
    echo "$(date +'%Y-%m-%d %H:%M:%S') - $message" | tee -a "$log_file" >&2
}


# 打开idea
open_idea(){
    log "$3 $2 下载完成"
    # shellcheck disable=SC2162
    read -p "是否打开IntelliJ IDEA？(y/n) 如果无法打开。请在DACS中将你的IDEA改成[IntelliJ IDEA Ultimate] " open_confirm
    if [ "$open_confirm" == "y" ]; then
        open -a "IntelliJ IDEA Ultimate" "$1"
    fi
}

# 格式化名字这种，去掉系统不支持的
format_name(){
    # shellcheck disable=SC2001
    echo "$1" | sed 's|/|_|g'
}

request_permission(){
  # shellcheck disable=SC2155
  local data=$(jq -n --arg write_repo "$1" \
     '{
       "write": [$write_repo],
       "read": [],
       "subject": "开发需求",
       "inform_member": "alvin.hu"
     }')
  # 发起请求并捕获响应
  RESPONSE=$(curl -s "https://vops.hszq8.com/app/api/v1/apply/create/asc/asc" \
    -H "Accept: application/json, text/plain, */*" \
    -H "Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6" \
    -H "Connection: keep-alive" \
    -H "Content-Type: application/json;charset=UTF-8" \
    -H "Cookie: vops_token=$2" \
    -H "Origin: https://vops.hszq8.com" \
    -H "Referer: https://vops.hszq8.com/app/permissions_request_asc" \
    -H "Sec-Fetch-Dest: empty" \
    -H "Sec-Fetch-Mode: cors" \
    -H "Sec-Fetch-Site: same-origin" \
    -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0" \
    -H 'sec-ch-ua: "Chromium";v="130", "Microsoft Edge";v="130", "Not?A_Brand";v="99"' \
    -H 'sec-ch-ua-mobile: ?0' \
    -H 'sec-ch-ua-platform: "macOS"' \
    --data-raw "$data")
  # 解析 JSON 响应并进行校验
  message=$(echo "$RESPONSE" | jq -r '.message')
  log "申请结果: $message 请检查申请结果(飞书审批)"
}

# 克隆项目 1. clone地址 2. 项目地址 3. 分支名字
clone_project(){
    # 检查项目文件夹是否存在
    if [ -d "$1" ]; then
        log "项目文件夹 '$1' 已经存在。跳过不处理"
        return 0
    fi

    # 执行克隆并捕获错误信息
    clone_output=$(git clone "$2" "$1" 2>&1)  # 捕获标准错误输出
    log "$clone_output"
    if echo "$clone_output" | grep -q "could not be found\|don't have permission"; then
        log "无权限访问仓库或仓库不存在：$2 尝试申请中..."
        request_permission "$2" "$4"
        return 1
    fi

    # 切换到指定分支
    cd "$1" && git checkout "$3"
    # shellcheck disable=SC2181
    if [ $? -ne 0 ]; then
        log "克隆 $2 失败"
        return 1
    fi

    return 0
}

# 写入配置的函数
write_config() {
    local key=$1
    local value=$2
    local file=$3
    # 对 value 进行转义，避免特殊字符引发 sed 替换失败
    local escaped_value
    escaped_value=$(echo "$value" | sed 's/[&/\]/\\&/g')
    # 如果 key 已存在，替换它的值；否则追加新的 key=value
    if grep -q "^$key=" "$file"; then
        # 替换已存在的键值对
        sed -i '' "s/^$key=.*/$key=$escaped_value/" "$file"
    else
        # 追加新的键值对
        echo "$key=$value" >> "$file"
    fi
}

# 读取配置的函数
read_config() {
    local key=$1
    local file=$2
    # 使用 grep 提取 key 的值，使用 `=` 分隔确保读取完整值
    value=$(grep -E "^$key=" "$file" | sed -E "s/^$key=//")
    echo "$value"
}
# 追加配置的函数
append_config() {
    local key=$1
    local new_value=$2
    local file=$3
    # 获取当前 key 的值
    # shellcheck disable=SC2155
    local old_value=$(read_config "$key" "$file")
    # 如果 key 存在且不为空，则追加新值；否则直接写入新值
    if [ -n "$old_value" ]; then
        # 确保不重复追加相同的值
        if [[ "$old_value" != *"$new_value"* ]]; then
            new_value="$old_value,$new_value"
        else
            return 0
        fi
    fi
    # 写入更新后的值
    write_config "$key" "$new_value" "$file"
}

# 处理发布单。返回ops项目信息
parse_url() {
  # 普通发布单
  if [[ $1 == *"flow_type"* && $1 == *"flow_id"* ]]; then
    log "普通发布单模式"
        # 解析URL参数
    flow_type=$(echo "$1" | awk -F'[?&]' '{for(i=1;i<=NF;i++){if($i ~ /^flow_type=/){split($i,a,"="); print a[2]}}}')
    flow_id=$(echo "$1" | awk -F'[?&]' '{for(i=1;i<=NF;i++){if($i ~ /^flow_id=/){split($i,a,"="); print a[2]}}}')
    # 检查是否成功提取了flow_type和flow_id
    if [ -z "$flow_type" ] || [ -z "$flow_id" ]; then
        log "错误：无法解析flow_type和flow_id，请检查输入的URL。流程终止。"
        exit 1
    fi
     if [ -n "$3" ]; then
        # 用户输入的默认位置存在且不为空字符串
        log "用户输入的默认位置为：$3"
        clone_dir="$clone_dir/$3"
      else
        detail_api_response=$(get_flow_detail "https://vops.hszq8.com/app/api/v1/flow/get_flow_detail?type=$flow_type&id=$flow_id" "$2")
        work_item_name=$(echo "$detail_api_response" | jq -r '.data.work_item_name')
        dev_port_label=$(echo "$detail_api_response" | jq -r '.data.dev_port_label')
        clone_dir="$clone_dir/$dev_port_label-$work_item_name"
      fi
    mkdir -p "$clone_dir"
    ops_config_file="$clone_dir/ops.properties"
    # 如果配置文件不存在，创建它
    if [ ! -f "$ops_config_file" ]; then
        touch "$ops_config_file"
    fi
    log "解析发布单 成功  flow_id：$flow_id 下载目录：$clone_dir"
    log "配置文件: $ops_config_file"
    append_config "type" "1" "$ops_config_file"
    write_config "ops_url" "$1" "$ops_config_file"
    write_config "ops_type" "发布单模式" "$ops_config_file"
    write_config "flow_id" "$flow_id" "$ops_config_file"
    write_config "flow_type" "$flow_type" "$ops_config_file"
    api_response=$(get_flow_project "https://vops.hszq8.com/app/api/v1/flow/get_app_and_branch?type=$flow_type&id=$flow_id" "$2")
    # 解析data里面的项目信息
    projects=$(echo "$api_response" | jq -r '.data | length')
    log "发布单中总项目个数: $projects"
     # shellcheck disable=SC2004
     # 初始化app_list为空字符串
    app_list=""
    # 先在主进程中构建app_list
    # shellcheck disable=SC2004
    for ((i=0; i<$projects; i++)); do
      # ops项目名
      app=$(echo "$api_response" | jq -r ".data[$i].app")
      flow_app_id=$(echo "$api_response" | jq -r ".data[$i].id")
      repo_url=$(format_repo_url "$(echo "$api_response" | jq -r ".data[$i].repo_url")")
      # 分支名
      branch=$(echo "$api_response" | jq -r ".data[$i].name")
      # 项目名。git地址中截取的 git@gitlab.inzwc.com:hst-intl/hst-mpg-team/hs-trade/hs-intl-cond.git
      # hs-intl-cond 可能有多个项目共用一个名字。
      # 项目名  hs-intl-cond  ops名字 hs-intl-cond-scheduler、hs-intl-cond-server
      repo_name=$(basename "$repo_url" .git)
      parent_repo_name="$repo_name"
      # 先获取一下打包指令
      # 提取 `common` 和 `command`
      common=$(echo "$api_response" | jq -r ".data[$i].common")
      command=$(echo "$common" | jq -r ".command" 2>/dev/null)
      # 判断 `common` 是否为空或为 null，并且 `command` 是否为空或为 null
      if [[ "$common" != "null" && -n "$common" && "$command" != "null" && -n "$command" ]]; then
        # 如果 `common` 和 `command` 都有效，执行逻辑
        # 提取 `-pl` 参数后面的值
        if [[ "$command" =~ -pl[[:space:]]+([^[:space:]]+) ]]; then
          pl_value="${BASH_REMATCH[1]}"
          log "$repo_name git地址对应的是目录，需要提取 -pl 参数值: $pl_value"
          repo_name=$(basename "$pl_value")
        fi
      fi
      # 项目名 对应 app名字
      write_config "project.$repo_name.opsName" "$app" "$ops_config_file"
      # 项目名
      write_config "project.$repo_name.flow_app_id" "$flow_app_id" "$ops_config_file"
      write_config "project.$app.path" "$repo_name" "$ops_config_file"
      write_config "project.$app.git.path" "$parent_repo_name" "$ops_config_file"
      write_config "project.$repo_name.source.branch" "$branch" "$ops_config_file"
      # 拼接app到app_list，使用逗号分隔
      if [ -z "$app_list" ]; then
          app_list="$app"    # 初始值时不加逗号
      else
          app_list="$app_list,$app"
      fi
      # 拼接app到app_list，使用逗号分隔
      if [ -z "$app_id_list" ]; then
          app_id_list="$flow_app_id"
      else
          app_id_list="$app_id_list,$flow_app_id"
      fi
    done
    log "$app_list 写入配置文件"
    ## 直接覆盖
    write_config "apps" "$app_list" "$ops_config_file"
    write_config "app_ids" "$app_id_list" "$ops_config_file"
    # 发布单原分支
    write_config "ops.source.branch" "$branch" "$ops_config_file"
    # shellcheck disable=SC2004
    for ((i=0; i<$projects; i++)); do
        # ops项目名
        app=$(echo "$api_response" | jq -r ".data[$i].app")
        plugin_list_exists=$(echo "$api_response" | jq -r ".data[$i].plugin_list | length > 0")
         if [ "$plugin_list_exists" = "true"  ]; then
           # 检查目录A是否存在
           if [ ! -d "$jz_clone_dir" ]; then
             log "错误：目录 $jz_clone_dir 不存在,请先维护一个基座基础地址"
             exit 1
           fi
           # 初始化变量
           found=0
           jz_target_dir=""
          # 遍历子目录
          for dir in "$jz_clone_dir"/*; do
            if [ -d "$dir" ]; then
              # hs-hk-admin-base-middle2-1 包含 hs-hk-admin-base
              subdir_name=$(basename "$dir")
              # 判断变量a是否包含子目录名
              if [[ $app == *"$subdir_name"* ]]; then
                log "匹配到子目录（$app 包含该目录名）"
                jz_target_dir="$dir"
                found=1
                break  # 只取第一个匹配项
              fi
            fi
          done


          jz_project_dir="$clone_dir/$app"
          if [ ! -d "$jz_project_dir" ]; then
            mkdir -p "$jz_project_dir"
          fi
          if [ ! -d "$jz_project_dir/dubboMetaData" ]; then
            mkdir -p "$jz_project_dir/dubboMetaData"
          fi
          if [ ! -d "$jz_project_dir/log" ]; then
            mkdir -p "$jz_project_dir/log"
          fi
          if [ ! -d "$jz_project_dir/hs_koupleless" ]; then
            mkdir -p "$jz_project_dir/hs_koupleless"
          fi
          # 输出结果
          log "插件基座：$app 匹配基座项目Git 远程地址： 基座项目路径：$jz_target_dir"
          plugin_count=$(echo "$api_response" | jq -r ".data[$i].plugin_list | length")
          log "检测到项目 $app 包含 $plugin_count 个插件"
          write_config "project.plugin.jz.$app.path" "$jz_target_dir" "$ops_config_file"
           for ((p=0; p<$plugin_count; p++)); do
              plugin_repo_url=$(format_repo_url "$(echo "$api_response" | jq -r ".data[$i].plugin_list[$p].repo_url")")
              plugin_branch=$(echo "$api_response" | jq -r ".data[$i].plugin_list[$p].name")
              plugin_app=$(echo "$api_response" | jq -r ".data[$i].plugin_list[$p].app")
              plugin_repo_name=$(basename "$plugin_repo_url" .git)
              plugin_repo_name_v2=$(basename "$plugin_repo_url" .git)
              # 先获取一下打包指令
              # 提取 `common` 和 `command`
              plugin_common=$(echo "$api_response" | jq -r ".data[$i].plugin_list[$p].common")
              plugin_command=$(echo "$plugin_common" | jq -r ".command" 2>/dev/null)
              # 判断 `common` 是否为空或为 null，并且 `command` 是否为空或为 null
              if [[ "$plugin_common" != "null" && -n "$plugin_common" && "$plugin_common" != "null" && -n "$plugin_common" ]]; then
                # 如果 `common` 和 `command` 都有效，执行逻辑
                # 提取 `-pl` 参数后面的值
                if [[ "$plugin_common" =~ -pl[[:space:]]+([^[:space:]]+) ]]; then
                  plugin_pl_value="${BASH_REMATCH[1]}"
                  log "$plugin_repo_name git地址对应的是目录，需要提取 -pl 参数值: $plugin_pl_value"
                  plugin_repo_name_v2=$(basename "$plugin_pl_value")
                fi
              fi
              plugin_flow_app_id=$(echo "$api_response" | jq -r ".data[$i].app_id")
              # git 项目名=ops 项目名
              write_config "project.plugin.$plugin_repo_name_v2.opsName" "$plugin_app" "$ops_config_file"
              # 子目录=父目录
              write_config "project.plugin.$plugin_repo_name_v2.father" "$plugin_repo_name" "$ops_config_file"
              # git 项目名=对应基座地址
              write_config "project.plugin.$plugin_repo_name_v2.baseProject" "$app" "$ops_config_file"
              # git 项目名=appId
              write_config "project.plugin.$plugin_repo_name_v2.flow_app_id" "$plugin_flow_app_id" "$ops_config_file"
              # git 项目名=基座地址
              write_config "project.plugin.$plugin_repo_name_v2.jz_path" "$jz_target_dir" "$ops_config_file"
              project_dir="$clone_dir/$app/$plugin_repo_name"
              {
              # 克隆插件项目（并行处理）
               project_dir="$clone_dir/$app/$plugin_repo_name"
               log "克隆插件项目：$plugin_repo_name 分支 $plugin_branch 到 $project_dir"
               clone_project "$project_dir" "$plugin_repo_url" "$plugin_branch" "$2"
               } &
           done
           wait
         else
            {
             # git地址。http的版本
             repo_url=$(format_repo_url "$(echo "$api_response" | jq -r ".data[$i].repo_url")")
             # 分支名
             branch=$(echo "$api_response" | jq -r ".data[$i].name")
             # ops项目名
             app=$(echo "$api_response" | jq -r ".data[$i].app")
             # 文件夹的名字 也是git项目名
             repo_name=$(basename "$repo_url" .git)
             log "项目名：$repo_name 分支名称: $branch, 仓库URL: $repo_url  app: $app"
             # 构建项目文件夹路径
             project_dir="$clone_dir/$repo_name"
             clone_project "$project_dir" "$repo_url" "$branch" "$2"
             } &
         fi
    done
  wait
  # shellcheck disable=SC2031
  open_idea "$clone_dir" "$1" "发布单"
  exit 1
  fi
  # 依赖发布单
  if [[ $1 == *"release/app"* || $1 == *"release/deps"* ]]; then
    log "依赖发布单模式"
    param=$(basename "$1")
    if [ -n "$3" ]; then
        # 用户输入的默认位置存在且不为空字符串
        log "用户输入的默认位置为：$3"
        clone_dir="$clone_dir/$3"
    else
      work_item_name=$(get_flow_detail "https://vops.hszq8.com/app/api/v1/release/$param/info" "$2" ".data.name")
      clone_dir="$clone_dir/$work_item_name"
    fi
    mkdir -p "$clone_dir"
    ops_config_file="$clone_dir/ops.properties"
    # 如果配置文件不存在，创建它
    if [ ! -f "$ops_config_file" ]; then
        touch "$ops_config_file"
    fi
    log "解析依赖发布单 成功  url参数：$param 下载目录：$clone_dir"
    log "配置文件: $ops_config_file"
    append_config "type" "2" "$ops_config_file"
    write_config "ops_support_url" "$1" "$ops_config_file"
    write_config "ops_type_support" "依赖发布单模式" "$ops_config_file"
    write_config "param" "$param" "$ops_config_file"
    api_response=$(get_flow_project "https://vops.hszq8.com/app/api/v1/release/$param/app" "$2")
     # 解析data里面的项目信息
     projects=$(echo "$api_response" | jq -r '.data | length')
     log "依赖发布单中总项目个数: $projects"
    # shellcheck disable=SC2004
    for ((i=0; i<$projects; i++)); do
      # ops项目名
      app=$(echo "$api_response" | jq -r ".data[$i].appname")
      repo_url=$(format_repo_url "$(echo "$api_response" | jq -r ".data[$i].scm")")
      # 分支名
      branch=$(echo "$api_response" | jq -r ".data[$i].branch")
      repo_name=$(basename "$repo_url" .git)
       # 提取 `common` 和 `command`
      common=$(echo "$api_response" | jq -r ".data[$i].common")
      command=$(echo "$common" | jq -r ".command" 2>/dev/null)
      # 判断 `common` 是否为空或为 null，并且 `command` 是否为空或为 null
      if [[ "$common" != "null" && -n "$common" && "$command" != "null" && -n "$command" ]]; then
        # 如果 `common` 和 `command` 都有效，执行逻辑
        # 提取 `-pl` 参数后面的值
        if [[ "$command" =~ -pl[[:space:]]+([^[:space:]]+) ]]; then
          pl_value="${BASH_REMATCH[1]}"
          log "$repo_name git地址对应的是目录，需要提取 -pl 参数值: $pl_value"
          repo_name="$pl_value"
        fi
      fi
      write_config "project.support.$repo_name.source.branch" "$branch" "$ops_config_file"
      # 项目名 对应 app名字
      write_config "project.support.$repo_name.opsName" "$app" "$ops_config_file"
      # 项目名
      write_config "project.support.$repo_name.flow_app_id" "$flow_app_id" "$ops_config_file"
      write_config "project.support.$app.path" "$repo_name" "$ops_config_file"
      # 拼接app到app_list，使用逗号分隔
      if [ -z "$app_list" ]; then
          app_list="$app"    # 初始值时不加逗号
      else
          app_list="$app_list,$app"
      fi
    done
    log "$app_list 写入配置文件"
    write_config "support_apps" "$app_list" "$ops_config_file"
    # 下载项目
     # shellcheck disable=SC2004
     for ((i=0; i<$projects; i++)); do
     {
       # git地址。http的版本
       repo_url=$(format_repo_url "$(echo "$api_response" | jq -r ".data[$i].scm")")
       # 分支名
       branch=$(echo "$api_response" | jq -r ".data[$i].branch")
       # ops项目名
       app=$(echo "$api_response" | jq -r ".data[$i].appname")
       # 文件夹的名字 也是git项目名
       repo_name=$(basename "$repo_url" .git)
       log "项目名：$repo_name 分支名称: $branch, 仓库URL: $repo_url  app: $app"
       # 构建项目文件夹路径
       project_dir="$clone_dir/$repo_name"
        # 检查项目文件夹是否存在
       clone_project "$project_dir" "$repo_url" "$branch" "$2"
       } &
     done
    wait
    # shellcheck disable=SC2031
    open_idea "$clone_dir" "$1" "依赖发布单"
    exit 1

  fi
  # 发布计划
  if [[ $1 == *"plan_detail"* ]]; then
    log "发布计划模式"
    id=$(echo "$1" | awk -F'[?&]' '{for(i=1;i<=NF;i++){if($i ~ /^id=/){split($i,a,"="); print a[2]}}}')
    if [ -z "$id" ]; then
        log "错误：无法解析id，请检查输入的URL。流程终止。"
        exit 1
    fi
    if [ -n "$3" ]; then
      # 用户输入的默认位置存在且不为空字符串
      log "用户输入的默认位置为：$3"
      clone_dir="$clone_dir/$3"
    else
      work_item_name=$(get_flow_detail "https://vops.hszq8.com/app/api/v1/flow_plan/detail/$id" "$2" ".data.title")
      clone_dir="$clone_dir/$work_item_name"
    fi
    mkdir -p "$clone_dir"
    ops_config_file="$clone_dir/ops.properties"
    # 如果配置文件不存在，创建它
    if [ ! -f "$ops_config_file" ]; then
        touch "$ops_config_file"
    fi
    log "解析发布计划 成功  id：id 下载目录：$clone_dir 配置文件: $ops_config_file"
    type=$(read_config "type" "$ops_config_file")
    # 遍历 type 的内容
    echo "$type" | tr ',' '\n' | while read -r item; do
      if [[ "$item" == "1" ]]; then
        echo "不允许和普通发布单并行操作，请更换目录"
        exit 1
      fi
    done
    # 发布计划
    write_config "type" "3" "$ops_config_file"
    write_config "plan_url" "$1" "$ops_config_file"
    write_config "plan_type" "发布计划模式" "$ops_config_file"
    write_config "plan_id" "$id" "$ops_config_file"
    api_response=$(get_flow_project "https://vops.hszq8.com/app/api/v1/flow_plan/plan_version_branch/$id" "$2")
    # 解析data里面的项目信息
    projects=$(echo "$api_response" | jq -r '.data | length')
    log "发布计划中总项目个数: $projects"

     # shellcheck disable=SC2004
     # 初始化app_list为空字符串
     branch=""
    app_list=""
    # 先在主进程中构建app_list
    # shellcheck disable=SC2004
    for ((i=0; i<$projects; i++)); do
      # ops项目名
      app=$(echo "$api_response" | jq -r ".data[$i].app")
      repo_url=$(format_repo_url "$(echo "$api_response" | jq -r ".data[$i].repo_url")")
      # 分支名
      branch=$(echo "$api_response" | jq -r ".data[$i].name")
      repo_name=$(basename "$repo_url" .git)
      # 拼接app到app_list，使用逗号分隔
      if [ -z "$app_list" ]; then
          app_list="$app"    # 初始值时不加逗号
      else
          app_list="$app_list,$app"
      fi
    done
    log "$app_list 写入配置文件"
    write_config "plan_apps" "$app_list"
    # 发布单原分支
    write_config "plan.source.branch" "$branch"
    # shellcheck disable=SC2004
    for ((i=0; i<$projects; i++)); do
    {
      # git地址。http的版本
      repo_url=$(format_repo_url "$(echo "$api_response" | jq -r ".data[$i].repo_url")")
      # 分支名
      branch=$(echo "$api_response" | jq -r ".data[$i].name")
      # ops项目名
      app=$(echo "$api_response" | jq -r ".data[$i].app")
      # 文件夹的名字 也是git项目名
      repo_name=$(basename "$repo_url" .git)
      log "项目名：$repo_name 分支名称: $branch, 仓库URL: $repo_url  app: $app"
      # 构建项目文件夹路径
      project_dir="$clone_dir/$repo_name"
      clone_project "$project_dir" "$repo_url" "$branch" "$2"
      } &
    done
    wait
    # shellcheck disable=SC2031
    open_idea "$clone_dir" "$1" "发布计划"
    exit 1
  fi
  log "错误：不支持的地址"
  exit 1
}



# 获取token
get_vops_token() {
  # 1. 调用接口获取git地址数组
  vops_result=$(curl -s "https://admin-feature.vbkrhk.com/auto-ai/vops/user/detail?userName=$1")
  log " 获取 $1 的登录态"
  local code
  local msg
  local data
  local ops_token
  local depart
  local name
  code=$(echo "$vops_result" | jq -r '.code')
  msg=$(echo "$vops_result" | jq -r '.msg')
  data=$(echo "$vops_result" | jq -r '.data')
   # 判断是否异常
  if [[ "$code" != "0" ]]; then
    log "登录异常，错误信息: $msg"
    exit 1
  fi
  # 检查 data 是否为空
  if [[ "$data" == "null" || -z "$data" ]]; then
    log "返回数据为空，请检查用户插件是否正确。"
    exit 1
  fi
  # 提取必要的字段
  ops_token=$(echo "$data" | jq -r '.opsToken')
  depart=$(echo "$data" | jq -r '.depart')
  name=$(echo "$data" | jq -r '.name')
   # 校验data是否有值
  if [ -z "$ops_token" ]; then
    log "请域内刷新一下ops"
    exit 1
  fi
  # 打印结果
  log "欢迎 $depart 的$name "
  echo "$ops_token"
}
# 获取 token
get_vops_token_by_auth() {
  local auth="$1"

  # 构建 base64 编码的 Authorization
  local basic_auth
  basic_auth=$(echo -n "$auth" | base64)

  # 发起 POST 请求
  local response
  response=$(curl -s -w "\n%{http_code}" -X POST "https://vops.hszq8.com/api/login" \
    -H "Authorization: Basic $basic_auth" \
    -H "Content-Type: application/json")

  # 拆分响应体和 HTTP 状态码
  local body
  local http_code
  body=$(echo "$response" | sed '$d')
  http_code=$(echo "$response" | tail -n1)

  # 状态码判断
  if [[ "$http_code" == "401" ]]; then
    echo "auth: $auth is invalid" >&2
    return 1
  fi

  if [[ "$http_code" != "200" ]]; then
    echo "getToken 失败: $body" >&2
    return 1
  fi

  # 解析 JSON 并判断状态
  local status
  status=$(echo "$body" | jq -r '.status')
  if [[ "$status" != "success" ]]; then
    local message
    message=$(echo "$body" | jq -r '.message')
    echo "getToken 失败 message: $message" >&2
    return 1
  fi

  # 提取 token
  local token
  token=$(echo "$body" | jq -r '.token')
  echo "$token"
}

# git地址换成http地址
format_repo_url2(){
  if [[ $1 == git@* ]]; then
    # 提取域名和仓库路径
    domain=$(echo $1 | sed -E 's/git@([^:]+):.*/\1/')
    path=$(echo $1 | sed -E 's/git@[^:]+:(.*)/\1/')
    # 构建 HTTP 地址
    repo_url="http://$domain/$path"
    echo "$repo_url"
  else
    echo "$1"
  fi
}
# git地址换成http地址
format_repo_url(){
  echo "$1"
}

# 获取发布单的名字
get_flow_detail(){
   api_detail_response=$(curl -s  "$1" \
            -H 'Accept: application/json, text/plain, */*' \
            -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6' \
            -H 'Connection: keep-alive' \
            -H "Cookie: vops_token=$2" \
            -H 'Referer: https://vops.hszq8.com/app/flow/flow_detail' \
            -H 'Sec-Fetch-Dest: empty' \
            -H 'Sec-Fetch-Mode: cors' \
            -H 'Sec-Fetch-Site: same-origin' \
            -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0' \
            -H 'sec-ch-ua: "Chromium";v="124", "Microsoft Edge";v="124", "Not-A.Brand";v="99"' \
            -H 'sec-ch-ua-mobile: ?0' \
            -H 'sec-ch-ua-platform: "macOS"')
          # 打印请求返回的body内容
    # 检查status是否为success
    status=$(echo "$api_detail_response" | jq -r '.status')
    if [ "$status" != "success" ]; then
      log "get_flow_detail调用失败，返回状态为 $status 。流程终止。"
      exit 1
    fi
    work_item_name=$(format_name "$(echo "$api_detail_response")")
    echo "$work_item_name"
}
# 获取发布单的项目
get_flow_project(){
  local url=$1
  local vops_token=$2
  # shellcheck disable=SC2129
  echo "$(date +'%Y-%m-%d %H:%M:%S') - 请求 URL: $url" >> "$log_file"
   api_response=$(curl -s "$url" \
        -H 'Accept: application/json, text/plain, */*' \
        -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6' \
        -H 'Connection: keep-alive' \
        -H "Cookie: vops_token=$vops_token" \
        -H 'Referer: https://vops.hszq8.com/app/flow/flow_detail' \
        -H 'Sec-Fetch-Dest: empty' \
        -H 'Sec-Fetch-Mode: cors' \
        -H 'Sec-Fetch-Site: same-origin' \
        -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0' \
        -H 'sec-ch-ua: "Chromium";v="124", "Microsoft Edge";v="124", "Not-A.Brand";v="99"' \
        -H 'sec-ch-ua-mobile: ?0' \
        -H 'sec-ch-ua-platform: "macOS"')
      # 检查status是否为success
      status=$(echo "$api_response" | jq -r '.status')
      if [ "$status" != "success" ]; then
        log "get_app_and_branch 调用失败，返回状态为 $status 。流程终止。"
        exit 1
      fi
      echo "$(date +'%Y-%m-%d %H:%M:%S') - 响应: $api_response" >> "$log_file"
      echo "$api_response"
}


# 定义帮助信息
show_help() {
   echo "用法: ops [选项 or url]"
   echo "即可快速获取发布单、依赖发布单、发布计划中的项目"
   echo "选项:"
   echo "  -r                   更新配置文件"
   echo "  url                  获取该发布单信息，拉取项目，如无权限，则自动申请权限。等待授权后，再自动下载项目"
   echo "  --help               显示此帮助信息"
   echo ""
}
init_check() {
    local input_path=$(pwd)
    # 提取直到 "Documents/" 的部分
    local ops_dir="${input_path%%/Documents/*}/Documents/ops/ops_global.properties"
    if [ ! -f "$ops_dir" ]; then
        ops_init
    fi
}
# 主流程
main() {
  # 初始化检查
  init_check
  # 检查参数是否为空
  if [ $# -eq 0 ]; then
    log "错误：请至少提供一个参数。"
    show_help
    exit 1
  fi
  # 获取用户输入的地址
  args=("$@")

  # 1. 获取能用的token

  if [[ $ops_auth_type -eq 1 ]]; then
     token=$(get_vops_token_by_auth "$ops_auth")
  else
     token=$(get_vops_token "$ops_user")
  fi
  log "获取 ops token: $token"
  # 解析命令行参数
  while [[ "${args[0]}" != "" ]]; do
    case "${args[0]}" in
      -r)
        # 重新加载ops
        ops_config_file="$PWD/ops.properties"
        # 如果配置文件不存在，创建它
        if [ ! -f "$ops_config_file" ]; then
            log "配置文件不存在，无法刷新"
            exit 1
        fi
        type=$(read_config "type" "$ops_config_file")
        # 遍历 type 的内容
        echo "$type" | tr ',' '\n' | while read -r item; do
          if [[ "$item" == "1" ]]; then
            ops_url=$(read_config "ops_url" "$ops_config_file")
            log "普通发布单刷新 $ops_url"
            if [ -z "$ops_url" ]; then
                log "普通发布单刷新 配置不存在，无法刷新"
                exit 1
            fi
            dops "$ops_url" "$(basename "$PWD")"
          fi
          if [[ "$item" == "2" ]]; then
            ops_url=$(read_config "ops_support_url" "$ops_config_file")
            log "依赖发布单刷新 $ops_url"
            if [ -z "$ops_url" ]; then
                log "依赖发布单刷新 配置不存在，无法刷新"
                exit 1
            fi
            dops "$ops_url" "$(basename "$PWD")"
          fi
          if [[ "$item" == "3" ]]; then
            ops_url=$(read_config "plan_url" "$ops_config_file")
            log "发布计划刷新 $ops_url"
            if [ -z "$ops_url" ]; then
                log "发布计划刷新 配置不存在，无法刷新"
                exit 1
            fi
            dops "$ops_url" "$(basename "$PWD")"
          fi
        done
        ;;
      --d)
        # 调试模式已在外层处理，这里只需要跳过这个参数
        shift
        ;;
      --help)
        show_help
        exit 0
        ;;
      *)
        ops_url=$(echo "${args[0]}" | sed 's/\\//g')
        ops_base_path="${args[1]}"
        log "地址：$ops_url 下载位置：$ops_base_path"
        parse_url "$ops_url" "$token" "$ops_base_path"
        ;;
    esac
    # 使用数组的shift
    args=("${args[@]:1}")
  done
}
# 检查是否启用调试模式
debug_mode=false
for arg in "$@"; do
  if [[ "$arg" == "--d" ]]; then
    debug_mode=true
    break
  fi
done
# 移除--d参数，避免干扰主流程处理
args=()
for arg in "$@"; do
  if [[ "$arg" != "--d" ]]; then
    args+=("$arg")
  fi
done
# 根据调试模式设置执行
if $debug_mode; then
  set -x
  main "${args[@]}"
  set +x
else
  set -e
  main "${args[@]}"
fi